import { Tile as TileLayer } from "ol/layer";
import Map from "ol/Map";
import XYZ from "ol/source/XYZ";
import View from "ol/View";
import { fromLonLat } from "ol/proj";

const token = "c0b9f333079bedccdea3867f66c049e2";

/**
 * 加载天地图矢量地图
 * @param {String} target 地图渲染的目标DOM元素
 * @param {Array} layer 需要叠加的图层
 * @param {Array<Number>} center 初始中心点经纬度
 * @param {Number} zoom 初始地图层级
 * @returns map实例
 */
export const loadVecTdt = (
  target,
  layersOverlay,
  center = [108.923611, 34.540833],
  zoom = 2
) => {
  let layers = [
    new TileLayer({
      source: new XYZ({
        url: `http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${token}`,
        attributions:
          '© All maps<a href="https://www.tianditu.gov.cn"> 天地图 </a>contributors. ',
        attributionsCollapsible: false,
      }),
    }),
    new TileLayer({
      source: new XYZ({
        url: `http://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${token}`,
      }),
    }),
  ];
  if (layersOverlay) {
    layersOverlay.forEach((layer) => {
      layers.push(layer);
    });
  }
  let view = new View({
    center: fromLonLat(center),
    zoom,
  });
  let map = new Map({
    layers, // 图层
    target: target, // 目标DOM元素
    view, // 视图配置
  });
  return map;
};
